import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter3demo/%E8%BD%AC%E5%9C%BA%E5%8A%A8%E7%94%BB/%E8%BD%AC%E5%9C%BA%E5%8A%A8%E7%94%BB%E4%B8%8D%E6%94%AF%E6%8C%81%E6%89%8B%E5%8A%BF%E6%BA%90%E7%A0%81/fade_scale_transition.dart';
void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Text Width Example'),
        ),
        body: HomePage(),
      ),
    );
  }
}
class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final globalKey = GlobalKey<AnimatedListState>();
  bool flag = true;
  List<String> list = ["第一条数据", "第二条数据"];

//删除
  Widget _buildItem(context, index) {
    return ListTile(
        key: ValueKey(index),
        title: Text(list[index]), //显示的数据
        trailing: IconButton(
          icon: Icon(Icons.delete), //删除的图标
// 点击时删除
          onPressed: () => _deleteItem(context, index),
        ));
  }

  _deleteItem(context, index) {
    if (flag == true) {
      flag = false;
      print(index);
//注意：删除后需要重新setState
      setState(() {
// 删除过程执行的是反向动画，animation.value 会从1变为0
        globalKey.currentState!.removeItem(
          index,
              (context, animation) {
            //执行删除
//注意先build然后再去删除
            var item = _buildItem(context, index);
            list.removeAt(index); //数组中删除数据
            return FadeTransition(
              //动画
              opacity: animation,
              child: item, //执行动画的元素
            );
          },
        );
      });
//解决快速删除bug 重置flag
      const timeout = Duration(milliseconds: 2000); //每2秒才删除一个
      Timer.periodic(timeout, (timer) {
        flag = true;
        timer.cancel();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Title'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            list.add("这是一个新增数据");
            globalKey.currentState!.insertItem(list.length - 1); //索引值为n-1
          });
        },
        child: const Icon(Icons.abc),
      ),
      body: AnimatedList(
          key: globalKey,
          initialItemCount: list.length,
          itemBuilder: (context, index, animation) {
            return FadeScaleTransition(
              animation: animation,
              child: _buildItem(context, index),
            );
          }),
    );
  }
}